(function ($) {
  var defaults = {
    pythonLib: {},
    gotAssets: {},
    MustWepyModules: ["turtle"],
    data: {
      apiDomain: 'http://175.24.98.133:9090',
      teachDomain: "https://manager.1717youxue.com",//'http://localhost:3000',
      ideDomain: "https://ide.1717youxue.com/python/",//"http://127.0.0.1/test/pyeditor/",
      shareDomain: "https://share.1717youxue.com/python_preview/share.html",//'http://127.0.0.1/test/python_preview/share.html',
      assetsDomain: "https://cdn.1717youxue.com/static/site/pyeditor/assets/",
      workId: null,
      workInfo: null,
      unitId: null,
      unitInfo: null,
      userData: null,

      // 默认未运行
      running: false,
      // 项目信息
      project: {
        // 作品名称
        name: "我的Python作品",
        xml: "",
        // 类型
        type: "webpy",
        // 语言
        lang: "python",
        // ID
        id: null,
        // 版本
        version: ""
      },
      // 编辑器 Dom 元素 ID
      code_area_id: "code_area",
      code_canvas_id: "code_canvas",
      console_id: "console",
      // 默认高度
      height: 600,
      // 是否全屏
      fullScreen: false
    } 
  }
  // 可以再自定义参数
  var opts = $.extend({}, defaults, {})
  // 为 jQuery 增加静态方法
  $.extend({
    getData: function() {
      return opts.data
    },
    onError: function (e) {
      notice(e.toString(), "error")
    },
    initInputCtrl: function () {
      // TODO 初始化输入框
    },
    checkCanvasInsert: function () {
      // TODO canvas 插入设置
    },
    encodeCharset: function (e) {
      try {
        e = decodeURIComponent(escape(e));
        var t = decodeURIComponent("%0A");
        e = e.replace(new RegExp(t, "gm"), decodeURIComponent("%0D%0A"))
      } catch (e) {
      }
      return e
    },
    closeInput: function (running) {
      opts.running = running
      if (running) {
        $("#runBtn").html("<i class='fa fa-stop fa-lg mr-2'></i>停止代码")
      } else {
        if (window.jqconsole.GetState() !== "output") {
          window.jqconsole.AbortPrompt()
        }
        $("#runBtn").html("<i class='fa fa-play fa-lg mr-2'></i>运行代码")
      }
    },
    innerOutput: function (e) {
      "\n" === e[e.length - 1] && (e = e.substr(0, e.length - 1)), e = $.encodeCharset(e), $.onOutput(e)
    },
    onOutput: function (text) {
      // 输出
      if (window.jqconsole) {
        window.jqconsole.Write(text+"\n", 'jqconsole-output');
      }
    },
    addTurtleAsset: function (e, t) {
      console.log(e)
      console.log(t)
      return null
    },
    getPythonLib: (o) => {
      // TODO 获取 python lib
      console.log(o)
    },
    addLib: function (e, t) {
      opts.pythonLib["src/lib/" + e + ".py"] = opts.pythonLib["src/lib/" + e + ".py"] || t
    },
    getLibs: function (modules, t) {
      var i = this, r = [], o = modules.map(function (module) {
        var o = module.replace(/\./g, "/") + ".py";
        return $.getPythonLib(o).then(function (n) {
          var o = module.split(".");
          if (r.push(module), !t) for (; o.length > 1;) i.addLib(o.shift(), "");
          t || i.addLib(o[0], n.data)
        }).catch(function (e) {
          return Promise.reject(e)
        })
      });
      return new Promise(function (e, t) {
        Promise.all(o).then(function () {
          if (o.length <= r.length) e(r); else {
            let i = new Error("python 加载不全");
            t(i)
          }
        }).catch(function (e) {
          t(e)
        })
      })
    },
    calibrateXY: function (e, t) {
      return [$('#code_canvas').width(), $('#code_canvas').height()]
    },
    builtinRead: function (x) {
      if (void 0 !== opts.pythonLib[x]) return opts.pythonLib[x];
      if (void 0 === window.Sk.builtinFiles || void 0 === window.Sk.builtinFiles.files[x]) throw new Error("File not found: " + x);
      var t = window.Sk.builtinFiles.files[x];
      if (-1 !== t.indexOf("raise NotImplementedError") && t.indexOf("raise NotImplementedError") <= 4) throw new Error("File not found: " + x);
      return window.Sk.builtinFiles.files[x]
    },
    inputFunction: function (prompt) {
      // prompt = $.encodeCharset(prompt)
      return new Promise((resolve, reject) => {
        // 程序交互
        window.jqconsole.Write(">>> " + prompt, 'jqconsole-output')
        let startPrompt = function () {
          // Start the prompt with history enabled.
          window.jqconsole.Prompt(true, function (input) {
            resolve(input);
          });
        };
        startPrompt();
      }).catch((err) => {
        notice(err, "error")
      })
    },
    initSk: function () {
      // 初始化 Sk
      window.Sk.pre = opts.data.console_id
      window.Sk.resetCompiler()
      window.Sk.configure({
        __future__: Sk.python3,
        yieldLimit: 200,
        execLimit: 6e5,
        output: $.innerOutput,
        read: $.builtinRead,
        python3: true,
        setTimeout: function (e) {
          function t(t, i) {
            return e.apply(this, arguments)
          }

          return t.toString = function () {
            return e.toString()
          }, t
        }(function (func, interval) {
          setTimeout(function () {
            try {
              func()
            } catch (e) {
              e.tp$name && "TimeLimitError" === e.tp$name || $.onError(e)
            }
          }, interval)
        }),
        inputfunTakesPrompt: true,
        inputfun: $.inputFunction
      })
      $.initInputCtrl()
      window.Sk.TurtleGraphics || (window.Sk.TurtleGraphics = {}), window.Sk.TurtleGraphics.target = opts.data.code_canvas_id
      window.Sk.TurtleGraphics.assets = window.Sk.TurtleGraphics.assets || {}, Object.assign(window.Sk.TurtleGraphics, {
        addAsset: $.addTurtleAsset,
        calibrateXY: $.calibrateXY
      })
      // 清空终端操作
      $.clearConsole()
      window.Sk.TurtleGraphics.reset && window.Sk.TurtleGraphics.reset(), window.Sk.inputfunTakesPrompt = true
      window.Sk && window.Sk.__future__ && (window.Sk.__future__.unicode_literals = true)

      window.Sk.TurtleGraphics.width = $('#code_canvas').width()
      window.Sk.TurtleGraphics.height = $('#code_canvas').height()
    },
    clearConsole: () => {
      // 清空终端操作
      window.jqconsole.Reset()
    },
    webPyResize: () => {
      // TODO 窗口重新设置
    },
    stopWebpy: function () {
      window.Sk.TurtleGraphics.reset && window.Sk.TurtleGraphics.reset()
      window.Sk && window.Sk.execLimit && (window.Sk.execLimit = 1), $.closeInput(false)
      $.onOutput("\n-- 程序停止运行 --\n")
    },
    run: function (code) {
      $.closeInput(true)
      return window.Sk.misceval.asyncToPromise(() => {
        $.checkCanvasInsert()
        return window.Sk.importMainWithBody("main", false, code, true)
      }).then($.onSuccess, $.onError).then(function () {
        $.webPyResize()
      })
    },
    fnPreCompileByWebpy: function (code) {
      let params = {
        grammar: true, // 语法
        mustWepy: false,
        modules: [],
        mustWepyModules: [],
        unSupportModules: [],
        supportModules: []
      }
      // 必须依赖
      let must_modules = opts.MustWepyModules;
      // code 为空，则返回
      if (!code) return params;
      let res = null;
      try {
        // 初始化 python
        $.initSk()
        // 预解析 code
        res = window.Sk.parse("main.py", code)
        console.log(res)
      } catch (e) {
        params.grammar = false
      }
      if (res) {
        let importFun = function (lib) {
          params.modules.push(lib)
          must_modules.find(function (_lib) {
            return _lib === lib
          }) && (params.mustWepy = true, params.mustWepyModules.push(lib));
          try {
            window.Sk.importModule(lib, false, true)
            params.supportModules.push(lib)
            // 打印支持信息
            console.log(params)
          } catch (err) {
            params.unSupportModules.push(lib)
          }
        };
        window.Sk.astFromParse(res.cst, "main.py", res.flags).body.forEach(function (e) {
          "Import" === e._astname ? e.names.forEach(function (e) {
            importFun(e.name.v)
          }) : "ImportFrom" === e._astname && importFun(e.module.v)
        })
      }
      return params
    },
    addTurtleImgAssets: function() {
      // TODO
    },
    setGotAssets: function (e) {
      opts.gotAssets[e] = true
    },
    getAssetsOfCode: function (code) {
      // TODO 如果存在图片资源，添加 Turtle 图片资源
      let images = []
      $.addTurtleImgAssets(images);
      // 预编译 python 获取支持信息
      let params = $.fnPreCompileByWebpy(code);
      // TODO 获取不支持 lib 文件
      return params.unSupportModules.length ? $.getLibs(params.unSupportModules).then(function () {
        let res = Object.keys(opts.pythonLib).map(function (str) {
          return opts.gotAssets[str] ? Promise.resolve() : $.getAssetsOfCode(opts.pythonLib[str]).then(function () {
            $.setGotAssets(str)
          })
        });
        return Promise.all(res)
      }).catch(function (e) {
        Promise.resolve(e)
      }) : Promise.resolve()
    },
    fnRunCodeWebpy: (code) => {
      if (opts.running) return $.stopWebpy()
      $.closeInput(true), $.runCode(code)
    },
    runCode: function(code) {
      $.getAssetsOfCode(code).then(function () {
        $.initSk(), $.run(code)
      })
    },
    onSuccess: function (module) {
      // 执行成功提示
      window.Cm.error_message = []
      window.jqconsole.Write("\n-- 程序执行完毕 --\n", 'jqconsole-output')
      $.closeInput(false)
      console.log(module)
      //$.clearMarks(window.Cm)
    },
    clearMarks: function(cm) {
      var state = cm.state.lint;
      if (state.hasGutter) cm.clearGutter('CodeMirror-lint-markers');
      for (var i = 0; i < state.marked.length; ++i)
        state.marked[i].clear();
      state.marked.length = 0;
    },
    onError: function (err) {
      // 异常输出
      let ret = err.toString();
      // 详细错误输出
      window.error_message = []
      if (err.traceback) {
        if (err.traceback.length > 0) {
          window.error_message.push({
            line: err.traceback[0].lineno,
            error: err.toString()
          })
        }
        for (let i = 0; i < err.traceback.length; i++) {
          ret += "\n  at " + err.traceback[i].filename + " line " + err.traceback[i].lineno;
          if ("colno" in err.traceback[i]) {
            ret += " column " + err.traceback[i].colno;
          }
        }
      }
      window.Cm.performLint()
      "TimeLimitError" === err.tp$name || window.jqconsole.Write("\n-- 程序执行异常: "+ (ret || "Unknown Error") +" --\n", 'jqconsole-output')
      $.closeInput(false)
      console.log(err)
    }
  })
})(window.jQuery)
$(document).ready(function(){
  $(window).resize(function(){
    setSize()
  });

  function python_validator (cm, updateLinting, options) {
    if ((window.error_message || 0).length > 0) {
      var errors = [{
        from: CodeMirror.Pos(window.error_message[0].line - 1),
        to: CodeMirror.Pos(window.error_message[0].line - 1),
        message: window.error_message[0].error,
        severity: "error"
      }]
      updateLinting(errors);
    }
  }
  // 编辑器初始化
  window.Cm = CodeMirror.fromTextArea(document.getElementById("code_area"), {
    mode: "python",
    lint: {
      "getAnnotations": python_validator,
      "async": true,
      "lintOnChange": false
    },
    hintOptions: {
      completeSingle: false,
    },
    parserfile: ["parsepython.js"],
    autofocus: true,
    theme: "default",
    lineNumbers: true,
    textWrapping: false,
    indentUnit: 4,
    autoMatchParens: true,
    // 匹配结束符号，比如"]、}"
    matchBrackets: true,
    // 自动闭合符号
    autoCloseBrackets: true,
    gutters: ["CodeMirror-lint-markers"],
    parserConfig: {'pythonVersion': 3, 'strictErrors': true}
  });
  window.Cm.setSize('auto','610px');
  window.Cm.on('keypress', function() {
    window.Cm.showHint()
  })
  // 输出初始化
  window.jqconsole = $('#console').jqconsole('', '')
  // 变成初始化
  $("#runBtn").click(function () {
    $.clearMarks(window.Cm)
    $.fnRunCodeWebpy(window.Cm.getValue())
  })
  $("#clearConsole").click(function(){
    $.clearConsole() 
  })
  $("#reset").click(function(){
    window.Cm.setValue("")
  })
  var codeName = window.getUrlParam2('unitName') ? decodeURI(decodeURI(window.getUrlParam2('unitName'))) : $.getData().project.name;
  $("#codeName").val(codeName);
  if (window.getUrlParam2("scene") == "getCode" || window.getUrlParam2("scene") == "startCode") {
    $("#profile").hide();
  }

  $("#login").click(function(){
    window.location.href = $.getData().teachDomain + "/user/login?goto=" + $.getData().ideDomain;
  });

  $("#profile").click(function(){
    if (window.getUserInfo()) {
      window.open($.getData().teachDomain + "/account/center");
    } else {
      $.messageTip.error({
  　　   message:"请先登录！",
        fadeInTimeOut : 0.3,   //滑入秒数
        contentTimeOut : 1.5,  //内容停留秒数
        fadeOutTimeOut : 0.3, ////滑出秒数
      });
    }
  });

  if (window.getUrlParam2("scene") == "view") {
    $("#publishBtn").hide();
  }

  if (window.getUrlParam2("isLive") || window.getUrlParam2("isCreate")) {
    $("#publishBtn").html('<i class="fa fa-save fa-lg mr-2"></i>保存');
    if (window.getUrlParam2("scene") == "startCode") {
      $("#save").show();
    }
  }

  $("#publishBtn").click(function() {
    window.saveCreateFile();
    // let projectTitle = $("#codeName").val();

    // if ($.trim(projectTitle) == "") {
    //     $.messageTip.error({
    // 　　   message:"作品名称不能为空！",
    //       fadeInTimeOut : 0.3,   //滑入秒数
    //       contentTimeOut : 1.5,  //内容停留秒数
    //       fadeOutTimeOut : 0.3, ////滑出秒数
    //     });
    //     return ;
    // }

  //   if (window.getUserInfo()) {
  //     if (window.getUrlParam2("scene") != "startCode" && window.getUrlParam2("scene") != "getCode") {
  //       let cover = "https://cdn.1717youxue.com/static/site/pyeditor/image/pythonPic.jpg";
  //       $("#projectCover").html('<image src="'+cover+'" style="width:320px;height:260px;margin-top:17px;" />');
  //       $('#publish').modal('toggle');
  //       $("#projectTitle").html(projectTitle);
  //     } else {
  //       //保存课堂练习
  //       if (window.getUrlParam2("scene") == "startCode") {
  //           window.uploadTeachingCode2();
  //       } else {
  //           window.uploadTeachingCode3();
  //       }
  //     }
  //   } else {
  //     $.messageTip.error({
  // 　　   message:"请先登录！",
  //       fadeInTimeOut : 0.3,   //滑入秒数
  //       contentTimeOut : 1.5,  //内容停留秒数
  //       fadeOutTimeOut : 0.3, ////滑出秒数
  //     });
  //   }
  });

  $("#save").click(function() {
    let projectTitle = $("#codeName").val();

    if ($.trim(projectTitle) == "") {
        $.messageTip.error({
    　　   message:"作品名称不能为空！",
          fadeInTimeOut : 0.3,   //滑入秒数
          contentTimeOut : 1.5,  //内容停留秒数
          fadeOutTimeOut : 0.3, ////滑出秒数
        });
        return ;
    }

    if (window.getUserInfo()) {
      let cover = "https://cdn.1717youxue.com/static/site/pyeditor/image/pythonPic.jpg";
      $("#projectCover").html('<image src="'+cover+'" style="width:320px;height:260px;margin-top:17px;" />');
      $('#publish').modal('toggle');
      $("#projectTitle").html(projectTitle);
    } else {
      $.messageTip.error({
  　　   message:"请先登录！",
        fadeInTimeOut : 0.3,   //滑入秒数
        contentTimeOut : 1.5,  //内容停留秒数
        fadeOutTimeOut : 0.3, ////滑出秒数
      });
    }
  });

  //初始化编辑器代码
  //var userData = window.getUserInfo();
  //if (userData) {
    // $("#notLogin").hide();
    // $("#isLogin").show();
    // $("#username").html($.getData().userData.realname);

    // let unitId = window.getUrlParam("unitId"); 
    // if (unitId) {
    //   var rs = window.getUnitInfo(window.getUrlParam("token"), unitId);
    //   if (rs) {
    //     $.getData().unitId = unitId;
    //     $.getData().unitInfo = rs;
    //     $("#codeName").val(rs.unitName+"课后作业");
    //     window.loadCode(rs.courseWork);
    //   }
    // } else {
    //   let workId = window.getUrlParam("workId");
    //   if (workId) {
    //     let rs = window.getWorkInfo(workId);
    //     if (rs) {
    //       $.getData().workId = workId;
    //       $.getData().workInfo = rs;
    //       $("#codeName").val(rs.workName);
    //       window.loadCode(rs.workFileUrl);
    //       //console.log(rs);
    //     }
    //   } else {
    //     if (window.getUrlParam2("codeUrl")) {
    //       window.loadCode('https://cdn.1717youxue.com/' + window.getUrlParam2("codeUrl"));
    //     }
    //   }
    // }
    if (window.getUrlParam2("codeUrl")) {
      window.loadCode('https://cdn.1717youxue.com/' + window.getUrlParam2("codeUrl"));
    }

    //检测pygme类型
    if (window.getUrlParam2("pygame")) {
      let token = window.getUrlParam("token");
      if (token) {
        $.ajax({
          async: false,
          url: $.getData().apiDomain + "/teaching/teachingPygameAssets/list" + (unitId ? "?unitId="+unitId : ""),
          headers: {
            "X-Access-Token": token
          },
          type: "get",
          success: function (data) {
            console.log(data);
            $.getData().userData["pygameAssets"] = data.records;

            $("#code_canvas").append('<ul id="asset_list" class="list-group list-group-flush"></ul>');
            for (var k in data.records) {
              $("#asset_list").append('<li class="list-group-item d-flex justify-content-between align-items-center">'+data.records[k].assetsName+'<div><button type="button" class="btn btn-primary" onclick="window.showAsset('+data.records[k]+')">查看</button><button type="button" class="btn btn-success" onclick="window.copyAsset('+data.records[k]+')">复制</button></div></li>');
            }
          },
          error: function () {
            $.getData().userData = null;
          }
        });
      }
    }
  //}
});

//保存创作作品
window.saveCreateFile = ()=>{
  //window.uploadCode();return ;
  let projectTitle = $("#codeName").val();
  if ($.trim(projectTitle) == "") {
    $.messageTip.error({
　　   message:"作品名称不能为空！",
      fadeInTimeOut : 0.3,   //滑入秒数
      contentTimeOut : 1.5,  //内容停留秒数
      fadeOutTimeOut : 0.3, ////滑出秒数
    });
  } else {
    window.saveWork(()=>{
      $.messageTip.success({
    　　   message:"作品保存成功！",
          fadeInTimeOut : 0.3,   //滑入秒数
          contentTimeOut : 1.5,  //内容停留秒数
          fadeOutTimeOut : 0.3, ////滑出秒数
        });
    });
  }
}

//上传作业代码(新)
window.uploadCode = (callback) => {
  let token = window.getUrlParam2("token");
  let isCreate = window.getUrlParam2("isCreate");
  var fd = new FormData();
  let file = window.getCodeFile();
  fd.append('file', file, 'project.py');
  $.ajax({
      headers: {
        "Authorization": token
      },
      type: 'POST',
      url: $.getData().apiDomain + '/api/work/uploadCode',
      data: fd,
      processData: false,
      contentType: false
  }).done(function(data) {
      console.log(data);
      if (callback) callback(data);
  });
}

window.showAsset = (data) => {
  window.open($.getData().assetsDomain+data.asset_id+"."+data.asset_format);
}

window.copyAsset = (data) => {
  //如果这里换为 input 则不支持换行
  var val = data.asset_name;
  var temp = document.createElement('textarea');
  temp.value = val;
  document.body.appendChild(temp);
  temp.select(); // 选择对象
  document.execCommand("Copy"); // 执行浏览器复制命令
  temp.style.display='none';
  $.messageTip.success({
　　   message: '复制成功',
      fadeInTimeOut : 0.3,   //滑入秒数
      contentTimeOut : 1.5,  //内容停留秒数
      fadeOutTimeOut : 0.3,  //滑出秒数
  });
}

window.pingHelper = ()=>{

}

window.getAssetsListObj = (code) => {
  let rs = {
    "type": "run",
    "lang": "python",
    "stuId": $.getData().userData.id,
    "xml": code,
    "assets": []
  };
  let assetsList=[];
  let pygameAssets = $.getData().userData.pygameAssets;
  if (pygameAssets) {
    let i=0;
    for (var k in pygameAssets) {
      if (code.indexOf(pygameAssets[k].asset_name) != -1) {
        assetsList.push({
          "assetId": pygameAssets[k].assetId,
          "dataFormat": pygameAssets[k].assetFormat,
          "index": i,
          "md5ext": pygameAssets[k].assetId+"."+pygameAssets[k].assetFormat,
          "name": pygameAssets[k].asset_name,
          "size": pygameAssets[k].asset_size
        });
        i++;
      }
    }

    rs["assets"]=assetsList;
  }
  return rs;
}

window.loadCode = (codeFile)=> {
  //加载远程代码
  fetch(codeFile).then(function(rsp) {
    window.showLoading(1)
    rsp.text().then(function(rs) {
      console.log(rs)
      //$("#code_area").val(rs);
      window.Cm.setValue(rs)
      window.showLoading(0)
    })
  })  
}

window.getUrlParam = (name) => {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  var r = window.parent.location.search.substr(1).match(reg);  //匹配目标参数
  if (r != null) return unescape(r[2]); return null; //返回参数值
}

window.getUrlParam2 = (name) => {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg);  //匹配目标参数
  if (r != null) return unescape(r[2]); return null; //返回参数值
}

window.showLoading = (s) => {
  s == 1 ? $("#loading_modal").show() : $("#loading_modal").hide();
}

//获取用户信息
window.getUserInfo = () => {
  let token = window.getUrlParam("token");
  if (token) {
    $.ajax({
        async: false,
        url: $.getData().apiDomain + "/api/sys/userinfo",
        headers: {
          "X-Access-Token": token
        },
        type: "get",
        success: function (data) {
          console.log(data);
          let userData = data.result;
          userData['nickname'] = userData.realname;
          if (userData['avatar'] == "") {
            userData['avatar'] = "https://cdn.1717youxue.com/static/site/common/images/default_avatar.png";
          }
          $.getData().userData = userData;
        },
        error: function () {
          $.getData().userData = null;
        }
    });
  }
  return $.getData().userData;
}

/**
 * 消息通知
 * @param msg 消息内容
 * @param type 消息类型
 */
function notice(msg, type) {
  // TODO 提示消息
  console.log(type + ": " + msg)
}

function setSize() {
  menu_height = 135
  h = $(window).height()-menu_height
  window.Cm.setSize('auto', h+'px');
  $('#main').height(h)
  $('#left').height(h)
  $('#right').height(h)
}

//分享作品
window.onShare = () => {
  if ($.trim($("#workDesc").val()) == "" || $.trim($("#operateDesc").val()) == "") {
    $.messageTip.error({
　　   message:"请填写完整再分享！",
      fadeInTimeOut : 0.3,   //滑入秒数
      contentTimeOut : 1.5,  //内容停留秒数
      fadeOutTimeOut : 0.3, ////滑出秒数
    });
  } else {
    window.saveWork((id) => {
      var shareUrl = $.getData().shareDomain + "?workId=" + id;
      console.log(shareUrl);
      $('#publish').modal('toggle');
      window.createCode('shareQrCode', shareUrl); 
      $('#showQrcode').modal('toggle');
      $('#shareQrCode img:first').css("margin", "0 auto");
    });
  }
}

//上传文件
window.uploadFile = (fileName, fileTag, filePath) => {
  var id = null;
  let token = window.getUrlParam("token");
  $.ajax({
    url: $.getData().apiDomain + '/api/system/sysFile/add',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    async: false,
    beforeSend: function (request) {
      request.setRequestHeader('Authorization', token)
    },
    data: JSON.stringify({
      fileType: 2,
      fileName: fileName,
      filePath: filePath,
      fileLocation: 2,
      fileTag: fileTag
    }),
    success: function (res) {
      console.log("=========================")
      console.log(res);
      if (res.code==0) {
        id = res.data.id
      }
    },
    error: function () {
    },
    complete: function () {
    }
  })
  console.log(id);
  return id;
}

//上传作业
window.uploadWork = (projectKey, projectTitle, callback) => {
  let token = window.getUrlParam("token");
  $.ajax({
    url: $.getData().apiDomain + '/api/teachingWork/submit',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    beforeSend: function (request) {
      request.setRequestHeader('Authorization', token)
    },
    data: JSON.stringify({
      //courseId: $.getData().unitId,
      workCover: "",
      workFile: projectKey,
      workName: projectTitle,
      id: $.getData().workId,
      workType: 3,
      workDesc: '',
      operateDesc: ''
    }),
    success: function (res) {
      console.log(res);
      //$.getData().workId = res.result.id;
      if (callback) callback();
    },
    error: function () {
      
    },
    complete: function () {
      window.showLoading(0);
    }
  })
}

//获取程序文件
window.getCodeFile = () => {
  var content = window.Cm.getValue();
  var filename = "project.py";

  var blob = new Blob([content], {
    type: "text/plain;charset=utf-8"
  });

  return new File([blob], filename, {type: "text/plain;charset=utf-8", lastModified: Date.now()});
}

//保存作品
window.saveWork = (callback) => {
  window.showLoading(1);
  //let image = window.dataURItoBlob(cover);
  //console.log(image);
  var fd = new FormData();
  //fd.append('files', image, 'cover.jpg');
  //fd.append('data', image);
  let token = window.getUrlParam("token");
  var filename = "project.py";
  let file = window.getCodeFile();

  fd.append('files', file, filename);
  $.ajax({
      headers: {
        "Authorization": token
      },
      type: 'POST',
      url: $.getData().apiDomain + '/api/teachingWork/uploadworkpy',
      data: fd,
      processData: false,
      contentType: false
  }).done(function(data) {
      console.log(data);
      //let coverKey = window.uploadFile(data.result.cover, "学生创作封面", data.result.cover);
      let projectKey = window.uploadFile(data.data.file, "学生创作文件py", data.data.file);
      let projectTitle = $("#codeName").val();
      window.uploadWork(projectKey, projectTitle, callback);
  });
}

//获取作品信息
window.getWorkInfo = (workId) => {
  var data = null;
  $.ajax({
    async: false,
    url: $.getData().apiDomain + '/api/teaching/teachingWork/studentWorkInfo',
    data: { workId: workId },
    success: function (res) {
      console.log(res);
      data = res.result;
    },
    error: function (e) {
    }
  })
  return data;
}

//获取课程作业信息
window.getUnitInfo = (access_token, unitId) => {
  var rs = null;
  $.ajax({
    async: false,
    url: $.getData().apiDomain + '/api/teaching/teachingCourseUnit/getUnitWorkInfo',
    data: {
      unitId: unitId
    },
    beforeSend: function(request) {
      request.setRequestHeader('X-Access-Token', access_token)
    },
    success: function(res) {
      console.log(res);
      rs = res.result;
    },
    error: function(e) {
      if (e.responseJSON.status == 500) {}
    }
  });
  return rs;
}

//生成二维码
window.createCode = (id, src) => {
  $('#' + id).html('')
  var qrcode = new QRCode(document.getElementById(id), {
    width: 300,
    height: 300
  })
  qrcode.makeCode(src)
}

//上传课堂练习(老师获取学生代码)
window.uploadTeachingCode = () => {
  window.showLoading(1);
  var fd = new FormData();
  let token = window.getUrlParam("token");
  let file = window.getCodeFile();

  //TODO 获取到项目文件
  //console.log(file)
  fd.append('files', file, 'project.py');
  $.ajax({
      headers: {
        "X-Access-Token": token
      },
      type: 'POST',
      url: $.getData().apiDomain + '/api/teaching/teachingLiveRoom/uploadTeachingCode/3',
      data: fd,
      processData: false,
      contentType: false
  }).done(function(data) {
      window.showLoading(0);
      console.log(data);
      window.parent.sendCodeToTeacher(data);
  });
}

//学生保存代码
window.uploadTeachingCode2 = () => {
  window.showLoading(1);
  var fd = new FormData();
  let token = window.getUrlParam("token");
  let file = window.getCodeFile();

  //TODO 获取到项目文件
  //console.log(file)
  fd.append('files', file, 'project.py');
  $.ajax({
      headers: {
        "X-Access-Token": token
      },
      type: 'POST',
      url: $.getData().apiDomain + '/api/teaching/teachingLiveRoom/uploadTeachingCode/3',
      data: fd,
      processData: false,
      contentType: false
  }).done(function(data) {
      window.showLoading(0);
      console.log(data);
      window.parent.saveCode(data);
  });
}

//老师帮学生修改代码
window.uploadTeachingCode3 = () => {
  window.showLoading(1);
  var fd = new FormData();
  let token = window.getUrlParam("token");
  let file = window.getCodeFile();

  //TODO 获取到项目文件
  //console.log(file)
  fd.append('files', file, 'project.py');
  $.ajax({
      headers: {
        "X-Access-Token": token
      },
      type: 'POST',
      url: $.getData().apiDomain + '/api/teaching/teachingLiveRoom/uploadTeachingCode/3',
      data: fd,
      processData: false,
      contentType: false
  }).done(function(data) {
      window.showLoading(0);
      console.log(data);
      window.parent.saveCode2(data);
  });
}